import time
from .mailtm import create_mail_account_with_fallback, poll_mail_code
from .register_api import check_send_code, send_verification_code, register_user
from .models import Account
from .database import db_session
from .log import logger, log_info, log_error, log_success, log_warning
from .utils import random_username, random_password
from .config import USERNAME_SUFFIX, MAIL_PREFIX, INVITE_CODE # Import necessary config
import datetime
import requests
# 单用户注册接口
def _register_single_account():
    """Handles the complete registration flow for a single account."""
    email, mail_password, token, err = create_mail_account_with_fallback()
    if err:
        log_error(f"无法创建临时邮箱: {err}")
        # Cannot proceed without email, return failure immediately
        return {"status": "fail", "error": f"创建临时邮箱失败: {err}"}

    # Generate target site credentials
    # Adjust username generation based on your needs (using prefix/suffix from Node.js example)
    # username = random_username(suffix=USERNAME_SUFFIX, length=8)
    # Use a simpler random username if prefix/suffix aren't strictly needed
    username = random_username(length=15)
    password = random_password(length=10) # Generate password for the target site

    account_info = {
        "email": email,
        "username": username,
        "password": password, # Target site password
        "invite_code": INVITE_CODE,
        "status": "pending",
        "error": None
    }

    # 1. Request verification code send from target site
    send_ok, send_err = send_verification_code(email)
    if not send_ok:
        account_info["status"] = "fail"
        account_info["error"] = f"请求发送验证码失败: {send_err}"
        log_error(f"[{username}/{email}] {account_info['error']}")
        return account_info

    # 2. Poll Mail.tm for the verification code
    code, poll_err = poll_mail_code(token) # Use the token obtained earlier
    if not code:
        account_info["status"] = "fail"
        account_info["error"] = f"获取验证码失败: {poll_err}"
        log_error(f"[{username}/{email}] {account_info['error']}")
        return account_info

    # 3. Register on the target site
    reg_ok, reg_err = register_user(username, password, code, email)
    if reg_ok:
        account_info["status"] = "success"
        log_success(f"[{username}/{email}] 注册流程成功完成")
    else:
        account_info["status"] = "fail"
        account_info["error"] = f"目标网站注册失败: {reg_err}"
        log_error(f"[{username}/{email}] {account_info['error']}")

    return account_info

# 批量注册接口
def batch_register(count):
    """Performs batch registration, including pre-check."""
    logs = []
    success_count = 0
    fail_count = 0

    # --- Pre-check Loop ---
    log_info("开始检测目标网站发码服务...")
    # Use a clearly distinct dummy email for testing that won't be registered
    dummy_email = f"13693176863a{int(time.time())}@qq.com"
    while not check_send_code(dummy_email):
        wait_msg = "目标网站发码服务当前不可用，将在5分钟后重试..."
        log_warning(wait_msg)
        # --- 日志推送开始 ---
        html_content = make_html_panel([wait_msg])
        ok, resp = pushplus_html_panel('c1a3952f501d4efba27eda0109d2ef35', "发码服务检测结果", html_content)
        if ok:
            log_info("日志已推送到 pushplus")
        else:
            log_warning(f"日志推送失败: {resp}")
        # --- 日志推送结束 ---
        time.sleep(1800)
    check_ok_msg = "目标网站发码服务检测通过，准备开始批量注册..."
    log_success(check_ok_msg)
    logs.append(check_ok_msg)
    # --- 日志推送开始 ---
    html_content = make_html_panel([check_ok_msg])
    ok, resp = pushplus_html_panel('c1a3952f501d4efba27eda0109d2ef35', "发码服务检测结果", html_content)
    if ok:
        log_info("日志已推送到 pushplus")
    else:
        log_warning(f"日志推送失败: {resp}")
    # --- 日志推送结束 ---
    # --- End Pre-check ---

    for i in range(count):
        log_info(f"--- 开始注册第 {i+1}/{count} 个账号 ---")
        result = _register_single_account()

        # Save result to database regardless of status
        try:
            # Check if email already exists (shouldn't happen often with random gen)
            existing = db_session.query(Account).filter_by(email=result.get("email")).first()
            if existing:
                 log_warning(f"邮箱 {result.get('email')} 已存在于数据库中，跳过保存。")
                 # Consider updating status if needed, but for now just skip duplicate insert
                 fail_count +=1 # Count as fail because we couldn't save the new attempt
                 logs.append(f"[{result.get('username')}/{result.get('email')}] 邮箱已存在，跳过保存。")
                 continue

            if result.get("email"): # Only save if we got an email
                acc = Account(
                    email=result["email"],
                    username=result["username"],
                    password=result["password"],
                    invite_code=result["invite_code"],
                    status=result["status"],
                    err_msg=result["error"],
                    is_deleted=False # Newly created are not deleted
                )
                db_session.add(acc)
                db_session.commit()
                log_info(f"账号信息已保存到数据库 (ID: {acc.id}, Status: {acc.status})")
            else:
                # This happens if email creation itself failed
                 log_error("无法保存账号到数据库，因为未能生成邮箱。")


            if result["status"] == "success":
                success_count += 1
                logs.append(f"[{result.get('username')}/{result.get('email')}] 注册成功")
            else:
                fail_count += 1
                logs.append(f"[{result.get('username')}/{result.get('email')}] 注册失败: {result.get('error', '未知错误')}")

        except Exception as e:
            db_session.rollback() # Rollback on error
            fail_count += 1
            err_save_msg = f"保存账号 {result.get('email')} 到数据库时出错: {e}"
            log_error(err_save_msg)
            logs.append(f"[DB Error/{result.get('email')}] {err_save_msg}")

        # Optional: Add a small delay between registrations
        time.sleep(1)

    final_msg = f"批量注册完成: 总计尝试 {count}, 成功 {success_count}, 失败 {fail_count}"
    log_success(final_msg)
    logs.append(final_msg)
    # ----------- 推送部分（只需添加这几行） -------------
    html_content = make_html_panel(logs)
    ok, resp = pushplus_html_panel('c1a3952f501d4efba27eda0109d2ef35', "批量注册结果", html_content)
    if ok:
        log_info("日志已推送到 pushplus")
    else:
        log_warning(f"日志推送失败: {resp}")
    # ---------------------------------------------------

    return logs, success_count, fail_count, 0 # Return 0 for skip count



def pushplus_html_panel(token, title, html_content):
    url = "http://www.pushplus.plus/send"
    payload = {
        "token": token,
        "title": title,
        "content": html_content,
        "channel": "wechat",
        "webhook": "pushplus"
    }
    headers = {"Content-Type": "application/json"}
    try:
        resp = requests.post(url, json=payload, headers=headers, timeout=8)
        return resp.ok, resp.text
    except Exception as e:
        return False, str(e)

def make_html_panel(logs):
    log_lines = ""
    for log in logs:
        if "不可用" in log or "失败" in log or "Error" in log:
            color = "#ffcccc"
        elif "通过" in log or "成功" in log:
            color = "#ccffcc"
        else:
            color = "#f0f0f0"
        log_lines += f'<tr><td style="padding:8px;background:{color};border-bottom:1px solid #eee;">{log}</td></tr>\n'
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    html = f"""<div style="max-width:520px;margin:24px auto;border-radius:8px;box-shadow:0 4px 16px #eee;">
    <div style="background:#4c8bf4;color:#fff;padding:16px 24px;border-radius:8px 8px 0 0;font-size:20px;font-weight:bold;">
        批量注册日志面板
    </div>
    <table style="width:100%;border-collapse:collapse;font-size:15px;">
        <tbody>
            {log_lines}
            <tr><td style="padding:8px;background:#fafafa;font-size:13px;text-align:right;color:#888;">检测时间：{now}</td></tr>
        </tbody>
    </table>
    </div>
    """
    return html